package com.j.lemon.learn.thread.produc1consum;

/**
 * @Author lijunjun
 * @Date 2019-04-22 15:33
 * @Description  synchronized + wait 和 notify 实现的传统的生产者消费者模式  ，两个线程交替对一个资源类进行加减,线程来控制唤醒逻辑
 */
public class TraditionalDemo2 {
    public static void main(String[] args) {
        ShareData2 shareData = new ShareData2();


        Thread t1 = new Thread(() -> {
            while(true){
                synchronized (shareData){
                    try {
                        Thread.sleep(1000);
                        shareData.notify();
                        shareData.add();
                        shareData.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        },"t1");
        Thread t2 = new Thread(() -> {
            while(true){
                synchronized (shareData){
                    try {
                        Thread.sleep(1000);
                        shareData.notify();
                        shareData.delete();
                        shareData.wait();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        },"t2");

        t1.start();
        t2.start();

    }
}

class ShareData2{
    int num = 0;

    public void add() {
        System.out.println(Thread.currentThread().getName()+"+1");
        num++;
    }

    public void delete() {
        System.out.println(Thread.currentThread().getName()+"-1");
        num--;
    }

}

